//
//  SerialPortReader.h
//  tg-reader
//
//  Created by Marius Veres on 3/16/14.
//  Copyright (c) 2014. All rights reserved.
//

#ifndef __SERIAL_PORT_READER__
#define __SERIAL_PORT_READER__

#include <boost/asio.hpp>

using namespace boost;

class SerialPortReader
{
public:
    /**
     * Constructor.
     * \param device port name, ex: "/dev/tty.MindWaveMobile-DevA" or ""\\\\.\\COM17""
     * \param baud_rate com speed, ex: 9600 or 57600
     * \throws boost::system::system_error if it cannot open the serial device
     */
    SerialPortReader(std::string port, unsigned int baud_rate) : _io(), _serial(_io, port)
    {
        _serial.set_option(asio::serial_port_base::baud_rate(baud_rate));
        _serial.set_option(asio::serial_port_base::character_size(8));
        _serial.set_option(asio::serial_port_base::stop_bits(asio::serial_port_base::stop_bits::one));
        _serial.set_option(asio::serial_port_base::parity(asio::serial_port_base::parity::none));
        _serial.set_option(asio::serial_port_base::flow_control(asio::serial_port_base::flow_control::none));
    }
    
    /**
     * Write a string to the serial device.
     * \param s string to write
     * \throws boost::system::system_error on failure
     */
    void writeString(std::string s)
    {
        boost::asio::write(_serial, asio::buffer(str.c_str(), str.size()));
    }
    
    /**
     * Read a character from the serial device.
     * \returns the read byte
     * \throws boost::system::system_error on failure
     */
    char readByte()
    {
        //Reading data char by char, code is optimized for simplicity, not speed
        
        char c;
        asio::read(_serial, asio::buffer(&c, 1));
        return c;
    }

private:
    boost::asio::io_service _io;
    boost::asio::serial_port _serial;
};

#endif //__SERIAL_PORT_READER__
